# -*- coding:utf-8 -*-
"""
顾客管理视图
create_by: zhoubing
"""

from django.shortcuts import render, redirect

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages


from .models import CustomerInfo
from .forms import AddCustomerForm


@login_required()
def index(request):
    """
    定义的管理首页
    """
    return render(request, "style/main/index.html")


@login_required()
def add_customer(request):
    """
    定义的添加顾客操作
    """
    ex_list = [
        'customer_memo', 'customer_tel', 'customer_qq', 'customer_email',
        'customer_weixin', 'customer_vocation'
    ]
    if request.method == 'POST':

        form = AddCustomerForm(request.POST)
        if form.is_valid():
            all_data = form.clean()
            CustomerInfo.objects.create(**all_data)
            messages.add_message(request, messages.SUCCESS, '添加成功！')
        else:
            messages.add_message(request, messages.ERROR, form.errors)
        return redirect('customers:add_customer')
    else:
        form = AddCustomerForm()
        return render(request, "style/customer/customer.html",
                      {'form': form, 'ex_list': ex_list})


@login_required()
def customer_list_json(request):
    """
    json数据
    """
    if request.method == 'GET':
        page = request.GET.get('page')
        limit = int(request.GET.get('limit'))

        customer_data = CustomerInfo.objects.all()

        # 分页

        paginator = Paginator(customer_data, limit)
        try:
            customer_list = [item.to_json() for item in paginator.page(page)]
            # for item_list in customer_list:
            #     print(item_list.get('customer_souce_id'))
            print(customer_list)
        except PageNotAnInteger:
            customer_list = [item.to_json() for item in paginator.page(1)]
        except EmptyPage:
            customer_list = [item.to_json()
                             for item in paginator.page(paginator.num_pages)]
        json_data = {
            "code": 0,
            "msg": "",
            "count": paginator.count,
            "data": customer_list
        }

    return JsonResponse(json_data)


@login_required()
def list_customer(request):
    """
    顾客列表
    """
    # for item in customer_data:
    #     print(item.to_json())
    return render(
        request, 'style/customer/customer_list.html'
    )
